<?php

namespace app\admin\controller;

use app\admin\business\UserBus;
use app\admin\model\User as UserModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;

class User extends Common
{

    public $userObj = null;
    public function __construct()
    {
        parent::__construct();
        $this->userObj = new UserModel();
    }

    /**
     * 用户列表
     */
    public function index()
    {
        $start_time = input('post.start_time');
        $end_time = input('post.end_time');
        $key = input('post.key','','trim');
        $page = input('page') ? input('page') : 1;
        $pageSize = input('limit') ? input('limit') : config('pageSize');
        $sort_by = input('sort_by') ? input('sort_by') : 'user_id';
        $sort_order = input('sort_order') ? input('sort_order') : 'desc';
        $where = [];
        if ($key) {
            $where[] = ['a.username|a.mobile|a.user_id', 'like', "%" . $key . "%"];
        }
        if ($start_time){
            $where[] = ['a.create_time','>',strtotime($start_time)];
        }
        if ($end_time){
            $where[] = ['a.create_time','<',strtotime($end_time)];
        }
        if (Request::isPost()) {
            $list = UserBus::getList($where,$sort_by,$sort_order,$pageSize,$page);
            return $result = ['code' => 0, 'msg' => '获取成功!', 'data' => $list['data'], 'count' => $list['total'], 'rel' => 1];
        }
        $data = UserBus::getUserStat();
        $this->assign('data',$data);
        return View::fetch();
    }


    /**
     * 修改状态
     */
    public function doStatus()
    {
        try {
            $user_id = input('request.user_id',0,'intval');
            $status = input('request.status',0,'intval');
            if (!$user_id) {
                return ['code' => 3000, 'msg' => '操作失败!'];
            }
            $result = $this->userObj->where('user_id',$user_id)->save(['status' => $status]);
            if ($result) {
                return ['code' => 0, 'msg' => '操作成功!'];
            }
            return ['code' => 3000, 'msg' => '操作失败!'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }



    /**
     * 添加用户
     * @return array|string
     */
    public function add(){
        try{
            if (request()->isPost()) {
                $data = input('post.','','trim');
                if (empty($data['password'])) {
                    return ['code' => 3000, 'msg' => '请设置登录密码!'];
                }
                unset($data['file']);
                unset($data['user_id']);
                $data['password'] = md5($data['password']);
                UserBus::addCheck($data);
                $result = $this->userObj->add($data);
                if ($result){
                    return ['code' => 0, 'msg' => '添加成功!'];
                }else{
                    return ['code' => 3000, 'msg' => '添加失败'];
                }
            } else {
                return View::fetch('edit');
            }
        }catch (\Exception $e){
            return ['code' => 3000, 'msg' => $e->getMessage()];
        }
    }


    /**
     * 编辑会员
     */
    public function edit()
    {
        try {
            if (request()->isPost()) {
                $data = input('post.','','trim');
                if (empty($data['password'])) {
                    unset($data['password']);
                }
                unset($data['file']);
                $this->userObj->updateByUserId($data['user_id'],$data);
                return ['code' => 0, 'msg' => '操作成功!'];
            } else {
                $user_id = input('request.user_id',0,'intval');
                $info = $this->userObj->getUserInfo($user_id);
                $info = $info->toArray();
                $this->assign('info', $info);
                return View::fetch();
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 删除
     * @return Array|array
     */
    public function doDelete(){
        try {
            $id = input('request.id');
            if (!$id) {
                return ['code' => 3000, 'msg' => '请选择要删除的数据!'];
            }
            if ($id == 10000){
                return ['code' => 3000, 'msg' => '系统一级用户不能删除!'];
            }
            $result = Db::name('user')->where('user_id',$id)->delete();
            if ($result) {
                return ['code' => 0, 'msg' => '删除成功!'];
            }
            return ['code' => 3000, 'msg' => '删除失败!'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }


    /**
     * 登录日志
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function loginlog(){
        $user_id = input('get.user_id', 0, 'intval');
        if (Request::isPost()) {
            $u_id = input("get.u_id");
            $start_time = input('post.start_time');
            $end_time = input('post.end_time');
            $page = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : config('pageSize');
            $sort_by = input('sort_by') ? input('sort_by') : 'user_loginlog_id';
            $sort_order = input('sort_order') ? input('sort_order') : 'desc';
            $where = [];
            if ($start_time){
                $where[] = ['a.login_time','>',strtotime($start_time)];
            }
            if ($end_time){
                $where[] = ['a.login_time','<',strtotime($end_time)];
            }
            $where[] = ['a.user_id', '=', $u_id];
            $list = UserBus::getLoginList($u_id,$where,$sort_by,$sort_order,$pageSize,$page);
            return $result = ['code' => 0, 'msg' => '获取成功!', 'data' => $list['data'], 'count' => $list['total'], 'rel' => 1];
        }
        $data = UserBus::getLoginStat($user_id);
        $this->assign('data',$data);
        View::assign('u_id', $user_id);
        return View::fetch();
    }


    /**
     * 导出到excel
     */
    public function exportExcel(){
        $start_time = input('get.start_time');
        $end_time = input('get.end_time');
        $key = input('get.key','','trim');
        $where = [];
        if ($key) {
            $where[] = ['a.username|a.mobile|shop_number|shop_name|shop_person', 'like', "%" . $key . "%"];
        }
        if ($start_time){
            $where[] = ['a.create_time','>',strtotime($start_time)];
        }
        if ($end_time){
            $where[] = ['a.create_time','<',strtotime($end_time)];
        }
        $list = Db::name('user')->where($where)->select()->toArray();
        foreach ($list as $k => $v){
            $list[$k]['create_time'] = date('Y-m-d H:i',$v['create_time']);
            $list[$k]['lastlogin_time'] = date('Y-m-d H:i',$v['lastlogin_time']);
        }
        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        //设置工作表标题名称
        $worksheet->setTitle('用户列表');
        $worksheet->calculateColumnWidths();
        // 设置列的宽度
        $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);
        //设置单元格内容
        $worksheet->setCellValueByColumnAndRow(1, 1, '店铺列表');
        $worksheet->setCellValueByColumnAndRow(1, 2, '编号');
        $worksheet->setCellValueByColumnAndRow(2, 2, '店铺名称');
        $worksheet->setCellValueByColumnAndRow(3, 2, '负责人');
        $worksheet->setCellValueByColumnAndRow(4, 2, '账户');
        $worksheet->setCellValueByColumnAndRow(5, 2, '最高库存量');
        $worksheet->setCellValueByColumnAndRow(6, 2, '手机号码');
        $worksheet->setCellValueByColumnAndRow(7, 2, '店铺地址');
        $worksheet->setCellValueByColumnAndRow(8, 2, '最后登录时间');
        $worksheet->setCellValueByColumnAndRow(9, 2, '创建时间');
        //合并单元格
        $worksheet->mergeCells('A1:I1');
        $styleArray = [
            'font' => [
                'bold' => true
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        //设置单元格样式
        $worksheet->getStyle('A1')->applyFromArray($styleArray)->getFont()->setSize(14);
        $worksheet->getStyle('A2:I2')->applyFromArray($styleArray)->getFont()->setSize(10);
        $len = count($list);
        for ($i=0; $i < $len; $i++) {
            $j = $i + 3; //从表格第3行开始
            $worksheet->setCellValueByColumnAndRow(1, $j, $list[$i]['shop_number']);
            $worksheet->setCellValueByColumnAndRow(2, $j, $list[$i]['shop_name']);
            $worksheet->setCellValueByColumnAndRow(3, $j, $list[$i]['shop_person']);
            $worksheet->setCellValueByColumnAndRow(4, $j, $list[$i]['username']);
            $worksheet->setCellValueByColumnAndRow(5, $j, $list[$i]['max_stock_number']);
            $worksheet->setCellValueByColumnAndRow(6, $j, $list[$i]['mobile']);
            $worksheet->setCellValueByColumnAndRow(7, $j, $list[$i]['shop_address']);
            $worksheet->setCellValueByColumnAndRow(8, $j, $list[$i]['lastlogin_time']);
            $worksheet->setCellValueByColumnAndRow(9, $j, $list[$i]['create_time']);
        }
        $styleArrayBody = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                    'color' => ['argb' => '666666'],
                ],
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        $total_jzInfo = $len + 2;
        //添加所有边框/居中
        $worksheet->getStyle('A1:I'.$total_jzInfo)->applyFromArray($styleArrayBody);
        $filename = '店铺列表.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }
}